<template>
  <div class="container">
    <section class="header">
      <div class="tabs">
        <div class="item first" :class="{ active: type == 1 }" @click="changeType(1)">
          <p class="title">{{ $t("fabi.main[0]") }}</p>
        </div>
        <div class="item" :class="{ active: type == 2 }" @click="changeType(2)">
          <p class="title">{{ $t("fabi.main[1]") }}</p>
        </div>
      </div>
    </section>
    <div class="main">
      <div class="item" :class="{toNext:type == 2 }">
        <div class="input">
          <span class="white before">￥</span>
          <input type="number" v-model="amount" @input="changeMoney" :placeholder="$t('fabi.main1[3]')" />
          <span class="white">CNY</span>
        </div>
      </div>
      <div class="toLink">
        <img :src="require('_img/tolink.png')" alt="">
      </div>
      <div class="item" :class="{toPrev:type == 2 }">
        <div class="input">
          <input type="number" v-model="qty" @input="changeQty" :placeholder="$t('fabi.main1[5]')" />
          <el-select class="select" :value="coin" @input="changeCoin" placeholder="请选择">
            <el-option v-for="item in coinList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <!-- <span>USDT</span> -->
        </div>
      </div>
      <div class="payway">
        <div class="label">{{ $t("fabi.main1[6]") }}</div>
        <div class="tabs">
          <div class="tab_item" :class="{ active: pay_method==2 }" @click="changPayType(2)">
            <div class="icon_box">
              <img src="../../assets/img/icon-alipay.png" alt="" />
            </div>
            <p>
              {{$t("fabi.main1[8]")}}
            </p>
          </div>
          <div class="tab_item" :class="{ active: pay_method==3 }" @click="changPayType(3)">
            <div class="icon_box">
              <img src="../../assets/img/icon_weixin.png" alt="" />
            </div>
            <p>
              {{$t("fabi.main1[9]")}}
            </p>
          </div>
          <div class="tab_item" :class="{ active: pay_method==1 }" @click="changPayType(1)">
            <div class="icon_box">
              <img src="../../assets/img/icon-yinlian.png" alt="" />
            </div>
            <p>
              {{$t("fabi.main1[7]")}}
            </p>
          </div>
        </div>
      </div>
      <div class="footer">
        <el-button class="confirm" type="primary" :loading="loading" @click="submit">
          {{type==1?'购买':'出售'}}
        </el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { market, quote, fast_order } from "@/api/fabitransaction";
import _ from "lodash";
export default {
  data() {
    return {
      type: 1,
      coin: '',
      coinList: [],
      orderList: [],
      pay_method: 2,
      amount: '',
      qty: '',
      loading: false,
      lastType:'amount'
    };
  },
  created() {
    this.market()
  },
  methods: {
    // 获取匹配到的广告
    async getAd(type, amount, call) {
      let side = this.type == 1 ? 'buy' : 'sell';
      this.loading = true;
      this.lastType = type
      try {
        this.orderList = await quote({ wid: this.coin, side, amount, type });
        let current = await this.getCurrentAd();
        call(current)
      } catch (e) {
        console.warn(e)
        this.clearNotLastType()
      }
      this.loading = false
    },
    // 获取当前支付方式的广告
    getCurrentAd() {
      return new Promise((resolve, reject) => {
        let current = this.orderList.find(item => item.pay_method == this.pay_method);
        if (current) {
          if (current.is_quote == 1) {
            resolve(current);
          } else {
            this.$message.error(`${current.pay_method_name}支付，暂未匹配到当前数额的广告`)
            throw new Error('无匹配结果')
          }
        } else {
          let coin = this.coinList.find(item => item.value == this.coin)
          if (coin) {
            if (!this.amount && !this.qty) {
              this.$message.error('请输入交易数额')
              return
            }
          }
          throw new Error('无匹配结果')
        }
      })
    },
    // 获取市场币种
    async market() {
      let res = await market();
      this.coinList = res.map(item => {
        return {
          label: item.code,
          value: item.wid
        }
      })
      if (this.coinList.length) this.coin = this.coinList[0].value
    },
    // 修改金额
    changeMoney: _.debounce(function () {
      if (this.amount == '') {
        this.clearData()
        return
      }
      this.getAd('amount', this.amount, (res) => {
        this.qty = res.quote_detail.qty
      })
    }, 500),
    // 修改币种
    changeCoin(val) {
      this.coin = val;
      if (this.lastType == 'amount') {
        this.changeMoney(this.amount);
      } else if (this.qty) {
        this.changeQty(this.qty);
      }
    },
    // 修改数量
    changeQty: _.debounce(function () {
      if (this.qty == '') {
        this.clearData()
        return
      }
      this.getAd('qty', this.qty, (res) => {
        this.amount = res.quote_detail.amount
      })
    }, 500),
    // 修改支付方式
    async changPayType(val) {
      this.pay_method = val;
      try{
        let current = await this.getCurrentAd();
        this.qty = current.quote_detail.qty;
        this.amount = current.quote_detail.amount;
      }catch(e){
        console.warn(e)
        this.clearNotLastType()
      }
    },
    // 修改交易方向
    changeType(type) {
      this.type = type;
      this.clearData()
    },
    // 发起交易
    async submit() {
      if (!this.amount || !this.qty) {
        this.$message.error('请输入交易数额')
        return
      }
      let current = await this.getCurrentAd();
      let quote_detail = current.quote_detail
      let data = {
        order_type: quote_detail.order_type,
        order_no: quote_detail.order_no,
        total_num: quote_detail.qty,
        total_price: quote_detail.amount,
        pay_method: current.pay_method
      }
      this.loading = true
      fast_order(data).then(res => {
        this.$message.success('操作成功');
        this.$router.push('/fabiorderdetail?order_no=' + res.order_no)
      }).finally(() => {
        this.loading = false
      })
    },
    // 清空数据
    clearData() {
      this.qty = '';
      this.amount = '';
      this.orderList = [];
    },
    // 清空非最后输入的输入款
    clearNotLastType(){
      if (this.lastType == 'amount') {
          this.qty = ''
        } else {
          this.amount = ''
        }
    }
  }
};
</script>
<style lang="less" scoped>
.container {
  min-height: 70vh;
  overflow: hidden;
  width: 980px;
  margin: 50px auto;
  color: #8e8e93;
  .header {
    margin: 30px 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .tabs {
      display: flex;
      .item {
        cursor: pointer;
        width: 224px;
        height: 60px;
        background: #19232f;
        border-radius: 4px 4px 0px 0px;
        text-align: center;
        line-height: 60px;
        .title {
          font-size: 20px;
        }
      }
      .active {
        background: #5a9cf8;
        .title {
          color: #fff;
        }
      }
    }
  }
  .main {
    border-radius: 4px;
    background-color: #182330;
    padding: 50px 160px 12px;
    .item {
      display: flex;
      justify-content: space-between;
      transition: all 0.3s;
      transform: translateY(0px);
      .label {
        width: 23%;
        color: #fff;
        font-size: 16px;
        line-height: 50px;
      }
      .input {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20px;
        background-color: #131c28;
        .before {
          margin-right: 10px;
          font-size: 20px;
        }
        input {
          flex: 1;
          height: 70px;
          background-color: #131c28;
          border-radius: 4px;
          color: #fff;
          font-size: 16px;
        }
        .select {
          width: 100px;
          /deep/ .el-input__inner {
            border: none;
          }
        }
        .white {
          color: #fff;
        }
      }
      @cal: 126px;
      &.toNext {
        transform: translateY(@cal);
      }
      &.toPrev {
        transform: translateY(-@cal);
      }
    }
    .toLink {
      img {
        display: block;
        width: 20px;
        margin-left: 26px;
      }
    }
    .payway .label {
      color: #fff;
      font-size: 12px;
      margin: 25px 0;
    }
    .tabs {
      display: flex;
      justify-content: space-between;
      .tab_item {
        width: 170px;
        height: 72px;
        background: rgba(19, 28, 40, 1);
        border-radius: 6px;
        cursor: pointer;
        font-size: 12px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        .icon_box {
          margin-bottom: 7px;
          position: relative;
          .tip {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
          }
        }
        &.active {
          border: 1px solid #6185e5;
        }
        img {
          vertical-align: middle;
        }
      }
    }
    .footer {
      display: flex;
      margin: 20px 0 10px;
      justify-content: center;
      .confirm {
        width: 40%;
      }
    }
  }
}
</style>
